package de.nordakademie.wpk.boerse.ui.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IPropertyListener;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;

import de.nordakademie.wpk.boerse.core.data.Depot;
import de.nordakademie.wpk.boerse.ui.editor.DepotEditor;
import de.nordakademie.wpk.boerse.ui.editor.DepotEditorInput;
import de.nordakademie.wpk.boerse.ui.view.UebersichtView;
import de.nordakademie.wpk.boerse.utils.BoerseTreeNode;

public class EditDepotHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IStructuredSelection currentSelection = (IStructuredSelection) HandlerUtil
				.getCurrentSelection(event);
		Depot selectedDepot;
		if (currentSelection != null && !currentSelection.isEmpty()) {
			BoerseTreeNode node = (BoerseTreeNode) currentSelection
					.getFirstElement();
			selectedDepot = (Depot) node.getValue();
		} else
			selectedDepot = new Depot("");
		DepotEditorInput editorInput = new DepotEditorInput(selectedDepot);
		// open Editor
		try {
			final IWorkbenchPage activePage = HandlerUtil
					.getActiveWorkbenchWindow(event).getActivePage();
			IEditorPart editor = activePage.openEditor(editorInput,
					DepotEditor.ID);
			editor.addPropertyListener(new IPropertyListener() {

				@Override
				public void propertyChanged(Object source, int propId) {
					if (propId == IEditorPart.PROP_INPUT) {
						UebersichtView view = (UebersichtView) activePage
								.findView(UebersichtView.ID);
						view.refresh();
					}
				}

			});
		} catch (PartInitException exception) {
			exception.printStackTrace();
		}
		return null;
	}

}
